#!/usr/bin/env python3
# -*- coding: utf-8 -*-

"""
比较改进前后的图片生成效果
"""

import sys
import os
import json
from pathlib import Path

# 添加项目根目录到 Python 路径
project_root = Path(__file__).parent
sys.path.insert(0, str(project_root))

# 加载环境变量
from dotenv import load_dotenv
load_dotenv()

from src.processors.lip_sync_generator import LipSyncGenerator


def test_original_prompt_generation():
    """测试原始提示词生成效果"""
    print("=== 测试原始提示词生成效果 ===")
    
    try:
        generator = LipSyncGenerator()
        
        # 测试对话数据
        test_dialogue = {
            "background_image": None,
            "dialogue": [
                {
                    "speaker": "left",
                    "text": "Welcome to our football analysis show! Today we'll be discussing the upcoming match between Manchester United and Liverpool.",
                    "voice_id": "pqHfZKP75CvOlQylNhV4"  # 中年男声 (26岁欧洲男人)
                },
                {
                    "speaker": "right", 
                    "text": "This is going to be an exciting match! Both teams are in great form this season.",
                    "voice_id": "Xb7hH8MSUJpSbSDYk0k2"  # 中年女声 (26岁非洲女人)
                }
            ]
        }
        
        # 使用原始方法生成提示词
        dialogue_json = json.dumps(test_dialogue)
        success, prompt_result = generator.generate_image_prompt(dialogue_json)
        
        if success:
            print("✓ 原始提示词生成成功!")
            print("生成的提示词:")
            print(prompt_result)
            
            # 生成图片
            output_path = project_root / "test_output" / "original_prompt_image.png"
            output_path.parent.mkdir(parents=True, exist_ok=True)
            
            image_success, image_result = generator.generate_image_from_prompt(prompt_result, str(output_path))
            if image_success:
                print(f"✓ 使用原始提示词生成图片成功: {image_result}")
                return str(output_path)
            else:
                print(f"✗ 使用原始提示词生成图片失败: {image_result}")
                return None
        else:
            print(f"✗ 原始提示词生成失败: {prompt_result}")
            return None
            
    except Exception as e:
        print(f"测试原始提示词时出错: {e}")
        return None


def test_improved_prompt_generation():
    """测试改进后的提示词生成效果"""
    print("\n=== 测试改进后的提示词生成效果 ===")
    
    try:
        generator = LipSyncGenerator()
        
        # 测试对话数据
        test_dialogue = {
            "background_image": None,
            "dialogue": [
                {
                    "speaker": "left",
                    "text": "Welcome to our football analysis show! Today we'll be discussing the upcoming match between Manchester United and Liverpool.",
                    "voice_id": "pqHfZKP75CvOlQylNhV4"  # 中年男声 (26岁欧洲男人)
                },
                {
                    "speaker": "right", 
                    "text": "This is going to be an exciting match! Both teams are in great form this season.",
                    "voice_id": "Xb7hH8MSUJpSbSDYk0k2"  # 中年女声 (26岁非洲女人)
                }
            ]
        }
        
        # 手动构建改进后的提示词
        improved_prompt = """A photorealistic image of a modern sports broadcast studio with two distinct commentators:
        
        Person 1 (Left side): Male, 26 years old, European descent, short brown hair, light skin, clean-shaven, wearing a navy-blue suit with a red tie, gesturing enthusiastically while analyzing football statistics on a screen.
        
        Person 2 (Right side): Female, 26 years old, African descent, dark skin, neatly braided hair, wearing a professional gray blazer, leaning forward with an analytical expression, pointing at tactical diagrams.
        
        Setting: Professional TV studio with large screens showing Manchester United and Liverpool team logos, modern glass desk, dynamic LED lighting in team colors, energetic yet professional atmosphere.
        
        Style: High-definition, photorealistic, broadcast quality, sharp focus on the two commentators. Clearly distinguish male and female characters with obvious gender features."""
        
        print("改进后的提示词:")
        print(improved_prompt)
        
        # 生成图片
        output_path = project_root / "test_output" / "improved_prompt_image.png"
        output_path.parent.mkdir(parents=True, exist_ok=True)
        
        image_success, image_result = generator.generate_image_from_prompt(improved_prompt, str(output_path))
        if image_success:
            print(f"✓ 使用改进提示词生成图片成功: {image_result}")
            return str(output_path)
        else:
            print(f"✗ 使用改进提示词生成图片失败: {image_result}")
            return None
            
    except Exception as e:
        print(f"测试改进提示词时出错: {e}")
        return None


def test_gender_emphasis_prompt():
    """测试强调性别的提示词"""
    print("\n=== 测试强调性别的提示词 ===")
    
    # 构建特别强调性别的提示词
    gender_emphasis_prompt = """Create a photorealistic image of a sports broadcast studio featuring two commentators with CLEARLY DISTINCT GENDER FEATURES:
    
    LEFT SIDE - MALE:
    - 26 years old
    - European descent
    - Short brown hair, fair skin, clean-shaven
    - Wearing a navy suit with red tie
    - Gesturing enthusiastically
    
    RIGHT SIDE - FEMALE:
    - 26 years old
    - African descent
    - Dark skin, neatly braided hair
    - Wearing a professional gray blazer
    - Leaning forward with analytical expression
    
    Background: Modern glass desk, large screens showing Manchester United and Liverpool logos, dynamic studio lighting.
    
    Style: High-definition, photorealistic, broadcast quality. MALE AND FEMALE CHARACTERS MUST BE CLEARLY DISTINGUISHABLE BY GENDER."""
    
    print("强调性别的提示词:")
    print(gender_emphasis_prompt)
    
    try:
        generator = LipSyncGenerator()
        output_path = project_root / "test_output" / "gender_emphasis_image.png"
        output_path.parent.mkdir(parents=True, exist_ok=True)
        
        image_success, image_result = generator.generate_image_from_prompt(gender_emphasis_prompt, str(output_path))
        if image_success:
            print(f"✓ 使用性别强调提示词生成图片成功: {image_result}")
            return str(output_path)
        else:
            print(f"✗ 使用性别强调提示词生成图片失败: {image_result}")
            return None
            
    except Exception as e:
        print(f"测试性别强调提示词时出错: {e}")
        return None


def main():
    """主函数"""
    print("开始比较改进前后的图片生成效果")
    print("=" * 60)
    
    # 检查API密钥
    dashscope_api_key = os.getenv("DASHSCOPE_API_KEY")
    if not dashscope_api_key:
        print("警告: 未设置 DASHSCOPE_API_KEY 环境变量")
        print("图片生成功能可能无法正常工作")
    
    # 测试原始提示词生成效果
    original_result = test_original_prompt_generation()
    
    # 测试改进后的提示词生成效果
    improved_result = test_improved_prompt_generation()
    
    # 测试强调性别的提示词
    gender_result = test_gender_emphasis_prompt()
    
    print("\n" + "=" * 60)
    print("测试完成")
    print("\n结果汇总:")
    print(f"  原始提示词效果: {'成功' if original_result else '失败'}")
    print(f"  改进提示词效果: {'成功' if improved_result else '失败'}")
    print(f"  性别强调效果: {'成功' if gender_result else '失败'}")
    print("\n请在 test_output 目录中查看生成的图片，比较不同方法的效果")


if __name__ == "__main__":
    main()